package escaleras.pkginterface;

import Dominio.Entidades.Jugador;
import Dominio.Fachada.Escalera;
import java.awt.event.KeyAdapter;
import java.awt.event.*;
import java.awt.event.KeyEvent;
import java.util.InputMismatchException;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JTextField;

public class Usuarios extends javax.swing.JInternalFrame {

    private Escalera sistema;

    public Usuarios(Escalera pSisEscalera) {
        initComponents();
        sistema = pSisEscalera;
        btnEditar.setListData(sistema.getListaDeJugadores().toArray());

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        txtAlias = new javax.swing.JTextField();
        lblAlias = new javax.swing.JLabel();
        lblNombre = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        txtEdad = new javax.swing.JTextField();
        lblEdad = new javax.swing.JLabel();
        btnAgregar = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();
        btnSalir = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        btnEditar = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();
        btnDelete = new javax.swing.JToggleButton();
        btnClear = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        setClosable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Reguistro de Jugadores");

        txtAlias.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        txtAlias.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtAliasActionPerformed(evt);
            }
        });

        lblAlias.setBackground(new java.awt.Color(0, 0, 0));
        lblAlias.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N
        lblAlias.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lblAlias.setText("Alias de usuario");

        lblNombre.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N
        lblNombre.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lblNombre.setText("Nombre de usuario");

        txtNombre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNombreActionPerformed(evt);
            }
        });
        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreKeyTyped(evt);
            }
        });

        txtEdad.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtEdadKeyTyped(evt);
            }
        });

        lblEdad.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N
        lblEdad.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lblEdad.setText("Edad");

        btnAgregar.setBackground(new java.awt.Color(255, 255, 255));
        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/escaleras/pkginterface/Recursos/Misc-New-Database-icon.png"))); // NOI18N
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        jProgressBar1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jProgressBar1.setStringPainted(true);

        btnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/escaleras/pkginterface/Recursos/Log-Out-icon.png"))); // NOI18N
        btnSalir.setMaximumSize(new java.awt.Dimension(69, 45));
        btnSalir.setMinimumSize(new java.awt.Dimension(69, 45));
        btnSalir.setPreferredSize(new java.awt.Dimension(69, 45));
        btnSalir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnSalirMouseClicked(evt);
            }
        });

        btnEditar.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        btnEditar.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                btnEditarValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(btnEditar);

        jLabel2.setBackground(new java.awt.Color(0, 0, 0));
        jLabel2.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N
        jLabel2.setText("Usuarios reguistrados");

        btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/escaleras/pkginterface/Recursos/Misc-Delete-Database-icon.png"))); // NOI18N
        btnDelete.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnDeleteMouseClicked(evt);
            }
        });

        btnClear.setIcon(new javax.swing.ImageIcon(getClass().getResource("/escaleras/pkginterface/Recursos/Actions-edit-clear-icon.png"))); // NOI18N
        btnClear.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnClearMouseClicked(evt);
            }
        });

        btnEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/escaleras/pkginterface/Recursos/update.png"))); // NOI18N
        btnEdit.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnEditMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(185, 185, 185)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblAlias, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblEdad))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtEdad, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtAlias, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(32, 32, 32)
                        .addComponent(btnClear))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 407, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnAgregar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnDelete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnEdit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(0, 114, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(55, 55, 55)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblAlias)
                            .addComponent(txtAlias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(btnClear))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblEdad)
                    .addComponent(txtEdad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(25, 25, 25)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnAgregar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEdit)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDelete)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jProgressBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnSalir, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(23, 23, 23))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtAliasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtAliasActionPerformed
        //controlo alias
    }//GEN-LAST:event_txtAliasActionPerformed

    private void txtNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNombreActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNombreActionPerformed

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        // agrego usuario
        try {

        String alias = txtAlias.getText();
        String nombre = txtNombre.getText();
        int edad = Integer.parseInt(txtEdad.getText());


        if (validarTexto(alias) && validarTexto(nombre) && edad < 120 && edad > 0) {
            if (!sistema.existeJugador(alias)) {
                Thread hilo1 = new HiloProcesos(jProgressBar1);
                hilo1.start();
                sistema.agregarJugador(sistema.crearJugador(nombre, alias, edad));
                lipioText();
                
            } else {
                JOptionPane.showMessageDialog(this, "El jugador ya existe");
            }
        } else {
            JOptionPane.showMessageDialog(this, "Tiene campos vacios o la edad no correspode");
        }
        btnEditar.setListData(sistema.getListaDeJugadores().toArray());
    } catch (Exception e) {
       JOptionPane.showMessageDialog(this, "Tiene campos vacios o la edad no correspode");
    }
       
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnSalirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSalirMouseClicked
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_btnSalirMouseClicked

    private void txtEdadKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtEdadKeyTyped
        // deja digitar solo numeros
        char c = evt.getKeyChar();
        if (!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE) || c == KeyEvent.VK_DELETE) {
            evt.consume();
        }
    }//GEN-LAST:event_txtEdadKeyTyped

    private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyTyped
        // deja digitar solo letras
        char c = evt.getKeyChar();
        if ((Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE) || c == KeyEvent.VK_DELETE) {
            evt.consume();
        }
    }//GEN-LAST:event_txtNombreKeyTyped

    private void btnEditarValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_btnEditarValueChanged

        Jugador unJugador = (Jugador) btnEditar.getSelectedValue();
        
        txtAlias.setText(unJugador.getAlias());
        txtNombre.setText(unJugador.getNombre());
        txtEdad.setText(unJugador.getEdad() + "");
        btnEditar.setEnabled(true);

    }//GEN-LAST:event_btnEditarValueChanged

    private void btnDeleteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnDeleteMouseClicked
        Jugador unJugador = (Jugador) btnEditar.getSelectedValue();
        if (!(unJugador == null)) {
            Thread hilo1 = new HiloProcesos(jProgressBar1);
            hilo1.start();
            sistema.borarJugador(unJugador);
            lipioText();
        } else {
            JOptionPane.showMessageDialog(this, "Para eliminar jugador debe seleccionarlo");
        }
        btnEditar.setListData(sistema.getListaDeJugadores().toArray());
    }//GEN-LAST:event_btnDeleteMouseClicked

    private void btnClearMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnClearMouseClicked
        txtAlias.setText("");
        txtNombre.setText("");
        txtEdad.setText("");
    }//GEN-LAST:event_btnClearMouseClicked

    private void btnEditMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEditMouseClicked
        boolean valido = true;
        
        Jugador unJugador = (Jugador) btnEditar.getSelectedValue();
        if (!(unJugador == null)) {
            try {
                int edad = Integer.parseInt(txtEdad.getText());
                String alias = unJugador.getAlias();
                String nombre = txtNombre.getText();

                if (!alias.equals(txtAlias.getText())) {
                    JOptionPane.showMessageDialog(this, "El alias no se mofificara,  el mismo no se puede cambiar");
                }

                if (validarTexto(nombre)) {
                    if (edad > 0)  {
                        if (edad < 150) {
                            if (validarTexto(alias)) {
                                sistema.updateJugador(unJugador, alias, nombre, edad);
                                Thread hilo1 = new HiloProcesos(jProgressBar1);
                                hilo1.start();
                                lipioText();

                            }
                        } else {
                            JOptionPane.showMessageDialog(this, "La edad tiene que ser menor a 150 ");
                        }
                    } else {
                        JOptionPane.showMessageDialog(this, "La edad tiene que ser mayor a cero ");
                    }

                } else {
                    JOptionPane.showMessageDialog(this, "El nombre del jugador no puede estar vacio");
                }

            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Dato ingresado invalido para la edad o  vacio");
            }
            btnEditar.setListData(sistema.getListaDeJugadores().toArray());
        } else {
            JOptionPane.showMessageDialog(this, "Para actualizar datos de jugador debe seleccionarlo");
        }
    }//GEN-LAST:event_btnEditMouseClicked

    /*Método que valida si un string es vacio*/
    private static boolean validarTexto(String unTexto) {
        boolean textoOk = false;
        if (!unTexto.equals("")) {
            textoOk = true;
        }
        return textoOk;
    }
    
    private void lipioText() {

        txtAlias.setText("");
        txtNombre.setText("");
        txtEdad.setText("");

    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnClear;
    private javax.swing.JToggleButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JList btnEditar;
    private javax.swing.JButton btnSalir;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JLabel lblAlias;
    private javax.swing.JLabel lblEdad;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JTextField txtAlias;
    private javax.swing.JTextField txtEdad;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables
}
